<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $企业微信企业客户API
*/
namespace core;
defined('BY_JYA') or exit('error');
class wxwork_userapi{
	protected $work_weixin = null;
	public function __construct($wxworkapp_id=0){
		if(!$wxworkapp_id){
			$wxworkapp_id=$_SESSION['wxworkapp_id'];
		}
		if(!$wxworkapp_id && $_SESSION['current_plugin'] && $_SESSION['current_plugin']!='core'){
			$pid=pdo_getcolumn('core_plugins',array('name'=>$_SESSION['current_plugin']),'id');
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('pid'=>$pid,'uniacid'=>$_SESSION['uniacid']),'id');
			$_SESSION['wxworkapp_id']=$wxworkapp_id;
		}
		if(!$wxworkapp_id){
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('default'=>1,'uniacid'=>$_SESSION['uniacid']),'id');
		}
		if(!$wxworkapp_id){
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('uniacid'=>$_SESSION['uniacid']),'id');
		}
		$this->uniacid=$_SESSION['uniacid'];
		if($wxworkapp_id){
			$_SESSION['wxworkapp_id']=$wxworkapp_id;
			$this->work_weixin=pdo_get('core_account_wxwork_app',array('id'=>$wxworkapp_id));
			$this->work_weixin['corpid']=pdo_getcolumn('core_account_wxwork',array('id'=>$this->work_weixin['wxwork_id']),'appid');
		}else{
			exi('请传入应用ID,或创建一个属于本场景下的应用！','error','core/wxwork.app/');
		}
		if(empty($this->work_weixin['corpid'])){
			if($_SESSION['this']=='manage'){
					exi('请先添加企业微信！并设置企业微信APPID','error','core/wxwork.list/');
			}else{
					return false;
					exi('请先添加企业微信。','error');
			}
		}
		if (empty($this->work_weixin['appid'])){
			exi('未绑定应用appid','error');
		}
		if (empty($this->work_weixin['corpid'])){
			exi('企业微信的corpid，不能为空！','error');
		}
		if($this->work_weixin['expire']<TIMESTAMP){
			$this->getAccessToken();
		}
	}
	public function get_corpid(){
		return $this->work_weixin['corpid'];
	}
	public function get_wxworkid(){
		return $this->work_weixin['wxwork_id'];
	}
	public function getAccessToken($continue=false){//获取access_token
		if($this->work_weixin['expire']>TIMESTAMP && !$continue){
			return $this->work_weixin['access_token'];
		}
		if(!$this->work_weixin['appsecret']){
			return false;
		}else{
			$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->work_weixin['corpid']."&corpsecret=".$this->work_weixin['appsecret'];
		}
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取企业微信应用凭证, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		if(empty($content['access_token'])) {
			exi('获取企业微信应用凭证, 请稍后重试！错误代码-' . $content['errcode'] . '，错误信息-' . $content['errmsg'],'error');
		}
		$this->work_weixin['access_token'] = $content['access_token'];
		$this->work_weixin['expire'] = TIMESTAMP + $content['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',array('access_token'=>$this->work_weixin['access_token'],'expire'=>$this->work_weixin['expire']),array('id'=>$this->work_weixin['id']));
		return $content['access_token'];
	}
	//获取客户列表
	public function get_member_list($userid){
		if(!$userid){
			exi('请传入企业成员的ID','error');
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token={access_token}&userid=".$userid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取客户列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		$list=$content['external_userid'];
		return $list;
	}
	//获取客户详情
	public function get_member_item($external_userid){
		if(!$external_userid){
			exi('请传入客户ID','error');
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token={access_token}&external_userid=".$external_userid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取客户详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		$memberitem=$content['external_contact'];
		return $memberitem;
	}
	//批量获取客户详情
	public function get_batch_member($external_userid,$cursor='',$limit=50){
		if(!$external_userid){
			exi('请传入员工ID','error');
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token={access_token}";
		$post=array(
			'userid'=>$external_userid,
			'cursor'=>$cursor,
			'limit'=>$limit,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			if($content['errcode']=='48002'){
				exi('没有权限：移步企业微信后台--客户联系--客户--API(点击展开)--可调用应用--选择本SCRM应用','error');
			}else{
				exi('批量获取客户详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
			}
		}
		return $content;
	}
	//修改客户备注信息
	public function set_member_remark($params){
		if(!$params['userid']){
			exi('请传入客户ID','error');
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token={access_token}";
		$post=array(
			'userid'=>$params['userid'],
			'external_userid'=>$params['external_userid'],
			'remark'=>$params['remark'],
			'description'=>$params['description'],
			'remark_company'=>$params['remark'],
			'remark_mobiles'=>$params['remark_mobiles'],
			'remark_pic_mediaid'=>$params['remark_pic_mediaid'],
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('修改客户备注信息失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//获取部门列表
	public function get_worker_bumen($bumenid=0){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={access_token}&id=".$bumenid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取部门列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['department'];
	}
	//获取员工列表
	public function get_worker_batch($bumenid=0,$fetch_child=1){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={access_token}&department_id=".$bumenid."&fetch_child=".$fetch_child;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取员工列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['userlist'];
	}
	//获取员工列表详情
	public function get_worker_batchinfo($bumenid=0,$fetch_child=1){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={access_token}&department_id=".$bumenid."&fetch_child=".$fetch_child;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取员工列表详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['userlist'];
	}
	//获取标签列表
	public function get_worker_tags(){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token={access_token}";
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取标签列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['taglist'];
	}
	//获取企业标签库
	public function get_member_tags($tag_id=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token={access_token}";
		$post=array(
			'tag_id'=>$tag_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取企业标签库失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//获取离职成员客户
	public function get_dimissionworker_members($page_id=0,$cursor='',$page_size=100){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_unassigned_list?access_token={access_token}";
		$post=array(
			'page_id'=>$page_id,
			'cursor'=>$cursor,
			'page_size'=>$page_size,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取离职成员客户失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取群列表
	public function get_qunlist($userid='',$cursor='',$limit=100){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token={access_token}";
		$owner_filter=$userid?array('userid_list'=>array(0=>$userid)):array();
		$post=array(
			'limit'=>$limit?:100,
			'cursor'=>$cursor,
			'owner_filter'=>$owner_filter,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取群列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取群详情
	public function get_qunitem($chat_id=''){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token={access_token}";
		$post=array(
			'chat_id'=>$chat_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取群详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['group_chat'];
	}
	//配置客户联系「联系我」方式
	public function add_contact_way($post){
		if($post['contact_id']){
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?access_token={access_token}";
		}else{
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token={access_token}";
		}
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('配置客户联系「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取企业已配置的「联系我」方式
	public function get_contact_way($config_id){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token={access_token}";
		$post=array(
			'config_id'=>$config_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取企业已配置的「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['contact_way'];
	}
	//删除企业已配置的「联系我」方式
	public function del_contact_way($config_id){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token={access_token}";
		$post=array(
			'config_id'=>$config_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('删除企业已配置的「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	public function getJssdkConfig(){//获取jssdk参数
		global $_AR;
		if(!$this->work_weixin['jsticket'] || $this->work_weixin['jsexpire']<TIMESTAMP){
			$this->getJsconfigTicket();
		}
		$nonceStr = random(16);
		$timestamp = TIMESTAMP;
		$url = $_AR['siteurl'];
		$string1 = "jsapi_ticket={$this->work_weixin['jsticket']}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
		$signature = sha1($string1);
		$config = array(
			"corpid"    => $this->work_weixin['corpid'],
			"agentid"    => $this->work_weixin['appid'],
			"nonceStr"	=> $nonceStr,
			"timestamp" => $timestamp,
			"signature" => $signature,
		);
		return $config;
	}
	public function getJsApiTicket(){
		global $_AR;
		$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={access_token}&type=jsapi";
		$result=$this->request($url);
		$record = array();
		$record['jsticket'] = $result['ticket'];
		$record['jsexpire'] = TIMESTAMP + $result['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',$record,array('id'=>$this->work_weixin['id']));
		$this->work_weixin['jsticket']=$record['jsticket'];
		return true;
	}
	public function getJsconfigTicket(){
		global $_AR;
		$url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={access_token}&type=agent_config";
		$result=$this->request($url);
		$record = array();
		$record['jsticket'] = $result['ticket'];
		$record['jsexpire'] = TIMESTAMP + $result['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',$record,array('id'=>$this->work_weixin['id']));
		$this->work_weixin['jsticket']=$record['jsticket'];
		return true;
	}
	/*
		执行接口请求
	*/
	private function request($url,$post=array()){
		if(is_array($post)){
			$post=ijson_encode($post);
		}
		$rurl=str_replace(array('{access_token}','ACCESS_TOKEN'),$this->work_weixin['access_token'],$url);
		$result=cfc('http')->request($rurl,$post);
		$result=@json_decode($result,true);		
		return $result;
	}
	//错误码
	public function error_code($code, $errmsg = '未知错误') {//获取错误详情
		global $_AR;
		$errors = array(
			'-1' => '系统繁忙',
			'0' => '请求成功',
			'300002' => '商品标题太长了！最长14个汉字',
			'300003' => '价格输入不合规（如：现价比原价大、传入价格非数字等）',
			'300018' => '图片尺寸超过300px*300px',
			'300006' => '图片上传失败（如：mediaID过期）',
			'300007' => '线上小程序版本不存在该链接,请重新上传小程序代码！',
			'300022'=>'此房间号不存在',
			'300023'=>'房间状态 拦截（当前房间状态不允许此操作）',
			'300024'=>'商品不存在',
			'300025'=>'商品审核未通过',
			'300026'=>'房间商品数量已经满额',
			'300027'=>'导入商品失败',
			'300028'=>'房间名称违规',
			'300029'=>'主播昵称违规',
			'300030'=>'主播微信号不合法',
			'300031'=>'直播间封面图不合规',
			'300032'=>'直播间分享图违规',
			'300033'=>'添加商品超过直播间上限',
			'300034'=>'主播微信昵称长度不符合要求',
			'300035'=>'主播微信号不存在',
			'300036'=>'主播微信号未实名认证,登录微信搜索--《直播小程序》--实名认证一下即可！',
			'40001' => '获取access_token时AppSecret错误，或者access_token无效',
			'40002' => '不合法的凭证类型',
			'40003' => '不合法的OpenID',
			'40004' => '不合法的媒体文件类型',
			'40005' => '不合法的文件类型',
			'40006' => '不合法的文件大小',
			'40007' => '不合法的媒体文件id',
			'40008' => '不合法的消息类型',
			'40009' => '不合法的图片文件大小',
			'40010' => '不合法的语音文件大小',
			'40011' => '不合法的视频文件大小',
			'40012' => '不合法的缩略图文件大小',
			'40013' => '不合法的APPID',
			'40014' => '不合法的access_token',
			'40015' => '不合法的菜单类型',
			'40016' => '不合法的按钮个数',
			'40017' => '不合法的按钮个数',
			'40018' => '不合法的按钮名字长度',
			'40019' => '不合法的按钮KEY长度',
			'40020' => '不合法的按钮URL长度',
			'40021' => '不合法的菜单版本号',
			'40022' => '不合法的子菜单级数',
			'40023' => '不合法的子菜单按钮个数',
			'40024' => '不合法的子菜单按钮类型',
			'40025' => '不合法的子菜单按钮名字长度',
			'40026' => '不合法的子菜单按钮KEY长度',
			'40027' => '不合法的子菜单按钮URL长度',
			'40028' => '不合法的自定义菜单使用用户',
			'40029' => '不合法的oauth_code',
			'40030' => '不合法的refresh_token',
			'40031' => '不合法的openid列表',
			'40032' => '不合法的openid列表长度',
			'40033' => '不合法的请求字符，不能包含\uxxxx格式的字符',
			'40035' => '不合法的参数',
			'40038' => '不合法的请求格式',
			'40039' => '不合法的URL长度',
			'40050' => '不合法的分组id',
			'40051' => '分组名字不合法',
			'41001' => '缺少access_token参数',
			'41002' => '缺少appid参数',
			'41003' => '缺少refresh_token参数',
			'41004' => '缺少secret参数',
			'41005' => '缺少多媒体文件数据',
			'41006' => '缺少media_id参数',
			'41007' => '缺少子菜单数据',
			'41008' => '缺少oauth code',
			'41009' => '缺少openid',
			'42001' => 'access_token超时',
			'42002' => 'refresh_token超时',
			'42003' => 'oauth_code超时',
			'43001' => '需要GET请求',
			'43002' => '需要POST请求',
			'43003' => '需要HTTPS请求',
			'43004' => '需要接收者关注',
			'43005' => '需要好友关系',
			'44001' => '多媒体文件为空',
			'44002' => 'POST的数据包为空',
			'44003' => '图文消息内容为空',
			'44004' => '文本消息内容为空',
			'45001' => '多媒体文件大小超过限制',
			'45002' => '消息内容超过限制',
			'45003' => '标题字段超过限制',
			'45004' => '描述字段超过限制',
			'45005' => '链接字段超过限制',
			'45006' => '图片链接字段超过限制',
			'45007' => '语音播放时间超过限制',
			'45008' => '图文消息超过限制',
			'45009' => '接口调用超过限制',
			'45010' => '创建菜单个数超过限制',
			'45015' => '回复时间超过限制',
			'45016' => '系统分组，不允许修改',
			'45017' => '分组名字过长',
			'45018' => '分组数量超过上限',
			'45056' => '创建的标签数过多，请注意不能超过100个',
			'45057' => '该标签下粉丝数超过10w，不允许直接删除',
			'45058' => '不能修改0/1/2这三个系统默认保留的标签',
			'45059' => '有粉丝身上的标签数已经超过限制',
			'45157' => '标签名非法，请注意不能和其他标签重名',
			'45158' => '标签名长度超过30个字节',
			'45159' => '非法的标签',
			'46001' => '不存在媒体数据',
			'46002' => '不存在的菜单版本',
			'46003' => '不存在的菜单数据',
			'46004' => '不存在的用户',
			'47001' => '解析JSON/XML内容错误',
			'48001' => 'api功能未授权',
			'50001' => '用户未授权该api',
			'40070' => '基本信息baseinfo中填写的库存信息SKU不合法。',
			'41011' => '必填字段不完整或不合法，参考相应接口。',
			'40056' => '无效code，请确认code长度在20个字符以内，且处于非异常状态（转赠、删除）。',
			'43009' => '无自定义SN权限，请参考开发者必读中的流程开通权限。',
			'43010' => '无储值权限,请参考开发者必读中的流程开通权限。',
			'43011' => '无积分权限,请参考开发者必读中的流程开通权限。',
			'40078' => '无效卡券，未通过审核，已被置为失效。',
			'40079' => '基本信息base_info中填写的date_info不合法或核销卡券未到生效时间。',
			'45021' => '文本字段超过长度限制，请参考相应字段说明。',
			'40080' => '卡券扩展信息cardext不合法。',
			'40097' => '基本信息base_info中填写的参数不合法。',
			'49004' => '签名错误。',
			'43012' => '无自定义cell跳转外链权限，请参考开发者必读中的申请流程开通权限。',
			'40099' => '该code已被核销。',
			'61005' => '缺少接入平台关键数据，等待微信开放平台推送数据，请十分钟后再试或是检查“授权事件接收URL”是否写错（index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;）',
			'61023' => '请重新授权接入该小程序',
			'85005'=>'小程序未关联小程序，无法通过自定义菜单跳转！',
			'40164'=>'服务器IP不在白名单导致接口请求失败！请前往公众平台——开发——基本配置——小程序开发信息——IP白名单处设置',
		);
		$code = strval($code);
		if($errors[$code]) {
			return $errors[$code];
		} else {
			return $errmsg;
		}
	}
}